<template>
	<view class="">
		<view class="navbar" :style="{ paddingTop: statusBarHeight + 'px', height: navBarHeight + 'px' }">
			<image src="@/static/logo.png" mode="widthFix"></image>
		</view>
		<!-- 切换语言 -->
		<view class="navbar-lan">
			<custom-picker
			      :value="lan"
			      :range="translatedArray"
			      :confirm-text="$t('确定')"
			      :cancel-text="$t('取消')"
			      @change="bindPickerChange"
			    >
			      <view class="content">
			      	<image :src="getImg" class="country"></image>
			      	<image src="@/static/right.png" mode="widthFix" class="ico"></image>
			      </view>
			    </custom-picker>
		 </view>
		<view class="loading-wrap">
			<view class="loading">
				<image src="@/static/bluetooth.png" style="width: 120rpx;height: 120rpx;"></image>
				<view class="pulse1"></view>
				<view class="pulse2"></view>
			</view>
			<view class="status">
				{{$t('正在搜索附近的设备')}}
				<view class="dot1"></view>
				<view class="dot2"></view>
				<view class="dot3"></view>
			</view>
		</view>
		<!-- 蓝牙动画 -->
		<view class="service-list">
			<view class="service-list-text">{{$t('请选择设备')}}</view>
			<view class="service-list-item" v-for="(item,index) in searchBluetList" :key="item.deviceId">
				<view class="service-list-item-left">
					<image :src="deviceId==item.deviceId || prev_deviceId == item.deviceId?s_active:active" mode="widthFix"></image>
					<text>{{item.name || item.localName}}</text>
				</view>
				<view class="service-list-item-right" @click="onConnect(item,index)">
					<template v-if="deviceId==item.deviceId && isConnect && onConnect(item,index)">
						<text class="rd">{{$t('自动连接中')}}...</text>
					</template>
					<template v-else>
						<text class="zt">{{$t('连接')}}</text>
					</template>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const UUID_SERVICE = "0000FFE1-0000-1000-8000-00805F9B34FB"; // 00001800-0000-1000-8000-00805F9B34FB
	const UUID_NOTIFY = "0000FFE2-0000-1000-8000-00805F9B34FB"; // 0000FFE3-0000-1000-8000-00805F9B34FB
	import { mapState, mapActions } from "vuex"
	import s_active from "@/static/s_active.png"
	import active from "@/static/s.png"
	import CustomPicker from '@/components/CustomPicker.vue';
	export default {
		components: {
			CustomPicker
		},
		computed: {
			...mapState({
				// .sort((a, b) => (b.RSSI - a.RSSI))
				searchBluetList: state => state.searchBluetList,
				deviceId: state => state.currentDevice.deviceId,
			}),
			// 动态翻译的 array 数据
			translatedArray() {
			  return [
				{ name: this.$t('languages[0].name'), value: 'zh' }, 
				{ name: this.$t('languages[1].name'), value: 'en' }, 
				{ name: this.$t('languages[2].name'), value: 'jp' }
			  ];
			},
			getImg(){
				return  `/static/${this.lan}.png`
			}
		},
		onShow() {
			// wx.getConnectedBluetoothDevices({
			// 	success: (res) => {
			// 		console.log("res.devices",res.devices)
			// 		res.devices.forEach(item => {
			// 			if(!this.searchBluetList.some(val => (val.deviceId == item.deviceId))){
			// 				uni.getBLEDeviceRSSI({
			// 					deviceId: item.deviceId,
			// 					success: ({RSSI}) => {
			// 						let searchBluetList = JSON.parse(JSON.stringify(this.searchBluetList));
			// 						item.RSSI = RSSI
			// 						searchBluetList.push(item);
			// 						this.$store.commit("setSearchBluetList",searchBluetList);
			// 					}
			// 				})
			// 			}
			// 		})
			// 	}
			// });	
			this.prev_deviceId = uni.getStorageSync("prev_deviceId");
		},
		data() {
			return {
				statusBarHeight: 0,
				navBarHeight: 0,
				active,
				s_active,
				isConnect: true,
				lan:'zh',
				prev_deviceId: ""
			}
		},
		created() {
		    const systemInfo = wx.getSystemInfoSync();
		    const statusBarHeight = systemInfo.statusBarHeight; // 获取状态栏高度
		    if (systemInfo.platform === 'android') {
		      this.navBarHeight = statusBarHeight + 48; // Android 导航栏高度
		    } else {
		      this.navBarHeight = statusBarHeight + 44; // iOS 导航栏高度
		    }
			const savedLanguage = uni.getStorageSync('language'); // 获取存储的语言
			  if (savedLanguage) {
			    this.lan = savedLanguage; // 设置语言
			    this.$i18n.locale = this.lan; // 根据存储的语言设置应用的语言
			  }
		},
		onPullDownRefresh() {
			// this.$store.commit("setSearchBluetList",[]);
			this.$store.state.searchBluetList = [];
			setTimeout(() => {
				uni.stopPullDownRefresh();
				this.$store.dispatch("stopSearchBlue",() => {
					uni.showToast({
						title: "success",
						icon: "success"
					});
					setTimeout(() => {
						this.$store.dispatch('searchBlue',true);
					}, 300);
				});
			},500)
		},
		onUnload() {
			// this.$store.commit("setSearchBluetList",[]);
			// this.$store.state.searchBluetList = [];
			this.$store.dispatch("stopSearchBlue");
		},
		methods: {
			...mapActions(["currentBlueData"]),
			bindPickerChange(index) {
				this.lan = this.translatedArray[index].value
				this.$i18n.locale = this.lan;
				uni.setStorageSync('language', this.lan); // 保存选择的语言
			},
			async onConnect(currentItem,index){
				this.isConnect = false;
				if(this.oldDeviceId == this.$store.state.currentDevice.deviceId) return uni.showToast({
									title:this.$t('请等待重试'),
									icon: 'none'
								});
				let item = JSON.parse(JSON.stringify(currentItem))
				this.oldDeviceId = item.deviceId;
				uni.showLoading({
					title: this.$t('正在匹配')
				});
				item.status = true;
				uni.createBLEConnection({
					deviceId: item.deviceId,
					success: () => {
						item.connected = true
						let info = wx.getSystemInfoSync()
						if(info.platform == "android"){
							uni.setBLEMTU({
								deviceId: item.deviceId,
								mtu: 512
							});
						}
						uni.getBLEDeviceServices({
						  deviceId: item.deviceId,
						  success: (data) => {
							let servicesIndex = data.services.findIndex(val => (val.uuid == UUID_SERVICE))
							if (servicesIndex!==-1) {
								let currentDevice = {
									deviceId: "",
									serviceId: "",
									characteristicId: ""
								}
								currentDevice.serviceId = UUID_SERVICE;
								currentDevice.deviceId = item.deviceId;
								uni.getBLEDeviceCharacteristics({
									deviceId: currentDevice.deviceId,
									serviceId: currentDevice.serviceId,
									success: response => {
										console.log("response.characteristics",response.characteristics)
										let characteristicsIndex = response.characteristics.findIndex(val => (val.uuid == UUID_NOTIFY))
										if(characteristicsIndex!==-1){
											currentDevice.characteristicId = UUID_NOTIFY;
											uni.notifyBLECharacteristicValueChange({
												state: true, 
												deviceId: currentDevice.deviceId,
												serviceId: currentDevice.serviceId,
												characteristicId: currentDevice.characteristicId, 
												success: (res) => {
													this.$store.state.currentDevice = currentDevice;
													item.status = false
													item.connected = true
													uni.setStorageSync("currentDevice",JSON.stringify(this.$store.state.currentDevice));
													setTimeout(() => {
														this.currentBlueData([0x1B, 0x03, 0x00, 0x01, 0x00, 0x62]);
														this.oldDeviceId = null;
														uni.setStorageSync("prev_deviceId",currentDevice.deviceId);
													});
											  },
											  fail: (err) => {
													item.status = false
													this.oldDeviceId = null
													console.log("notifyBLECharacteristicValueChange:err",err)
													uni.showToast({
														title:err.errMsg,
														icon: "error"
													})
											  },
											  // complete: () => uni.hideLoading()
											})
										}else{
											uni.showToast({
												title:this.$t('未能找到Notify特征值'),
												icon: 'none'
											});
											item.status = false
											uni.hideLoading()
											this.oldDeviceId = null
										}
									},
									fail: err => {
										item.status = false
										uni.hideLoading()
										this.oldDeviceId = null
										this.$store.commit("setSearchBluetListItem", {item,index})
										console.log("err:getBLEDeviceCharacteristics",err)
									}
								});
							}else{
								uni.showToast({
									title:this.$t('未能找到services特征值'),
									icon: 'none'
								});
								item.status = false
								uni.hideLoading()
								this.oldDeviceId = null
							}
						  },
						  fail: err => {
							item.status = false
							uni.hideLoading()
							this.oldDeviceId = null
							this.$store.commit("setSearchBluetListItem", {item,index})
							console.log("err:getBLEDeviceServices",err)
						  }
						});
					},
					fail: err => {
						console.log("err:createBLEConnection",err)
						item.status = false
						uni.hideLoading()
						this.oldDeviceId = null
						this.$store.commit("setSearchBluetListItem", {item,index})
						uni.showToast({
							title: this.$t('连接失败'),
							icon: "error"
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.navbar{
		position: relative;
		border-bottom: 1px solid #eee;
		image{
			width: 180rpx;
			position: absolute;
			bottom: 0;
			left: 20rpx;
		}
		
	}
	.navbar-lan{
		width: 100px;
		padding: 10px 0 0 20rpx;
		.content{
			width: 80rpx;
			border: 1px solid #ded7d7;
			display: flex;
			align-items: center;
			border-radius: 100rpx;
			justify-content: space-between;
			padding: 5rpx;
			box-sizing: border-box;
		}
	    .country{
			width: 32rpx;
			height: 32rpx;
			border-radius: 100%;
			flex-shrink: 0;
		}
		.ico{
			width: 30rpx;
			height: 30rpx;
		}
	}
	.loading-wrap {
			    text-align: center;
			    padding: 50rpx;
			    .loading {
			      width: 120rpx;
			      height: 120rpx;
			      position: relative;
			      z-index: 2;
			      margin: 80rpx auto;
			
			      .pulse1,
			      .pulse2 {
			        position: absolute;
			        width: 120rpx;
			        height: 120rpx;
			        left: 50%;
			        top: 0;
			        margin-left: -60rpx;
			        background: #2dc2b0;
			        border-radius: 50%;
			        opacity: 0;
			        z-index: -1;
			        box-shadow: 1px 1px 15px #a8e5df;
			      }
			
			      .pulse1 {
			        animation: warn1 1.5s linear;
			        animation-iteration-count: infinite;
			      }
			
			      .pulse2 {
			        animation: warn2 1.5s linear;
			        animation-iteration-count: infinite;
			      }
			
			      @keyframes warn1 {
			        0% {
			          transform: scale(1);
			          opacity: 0.3;
			        }
			
			        25% {
			          transform: scale(1.2);
			          opacity: 0.13;
			        }
			
			        50% {
			          transform: scale(1.4);
			          opacity: 0.1;
			        }
			
			        75% {
			          transform: scale(1.6);
			          opacity: 0.06;
			        }
			
			        100% {
			          transform: scale(1.8);
			          opacity: 0.04;
			        }
			      }
			
			      @keyframes warn2 {
			        0% {
			          transform: scale(0.8);
			          opacity: 0.04;
			        }
			
			        25% {
			          transform: scale(0.8);
			          opacity: 0.17;
			        }
			
			        50% {
			          transform: scale(1);
			          opacity: 0.14;
			        }
			
			        75% {
			          transform: scale(1.2);
			          opacity: 0.11;
			        }
			
			        100% {
			          transform: scale(1.4);
			          opacity: 0.04;
			        }
			      }
			    }
			
			    .status {
			      display: flex;
			      align-items: center;
				  justify-content: center;
			      ::v-deep .u-badge {
			        margin-right: 10rpx;
			      }
			
			      .dot1,
			      .dot2,
			      .dot3 {
			        width: 10rpx;
			        height: 10rpx;
			        border-radius: 50%;
			        margin: 10rpx;
			      }
			
			      .dot1 {
			        animation: jump 1.6s -0.32s linear infinite;
			        background: #63b916;
			      }
			      .dot2 {
			        animation: jump 1.6s -0.16s linear infinite;
			        background: #63b916;
			      }
			      .dot3 {
			        animation: jump 1.6s linear infinite;
			        background: #63b916;
			      }
			
			      @keyframes jump {
			        0%,
			        80%,
			        100% {
			          -webkit-transform: scale(0);
			          transform: scale(0);
			        }
			        40% {
			          -webkit-transform: scale(2);
			          transform: scale(2);
			        }
			      }
			    }
			  }
	
.service-list{
	padding: 0 20rpx;
	margin: 50rpx 0;
	&-text{
		font-size: 32rpx;
	}
	&-item{
		margin-top: 50rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		&-left{
			display: flex;
			align-items: center;
			image{
				width: 80rpx;
				margin-right: 10rpx;
			}
		}
		&-right{
			flex: 0 0 240rpx;
			text-align: right;
			// text{
			// 	margin-left: 30rpx;
			// }
			.zt{
				color: #2DC2B0;
			}
			.rd{
				color: #FF4D4F;
			}
		}
	}
}
</style>
